<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.username"
        placeholder="昵称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="success"
        icon="el-icon-plus"
        @click="handleCreate"
      >
        新增
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="false"
      :data="tableData"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" align="center" width="80">
        <template slot-scope="{ row }">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="160px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.gmtDatetime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="昵称" width="150px" align="center">
        <template slot-scope="{ row }">
          <span class="link-type" @click="handleUpdate(row)">{{
            row.username
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色" width="200px" align="center">
        <template slot-scope="{ row }">
          <el-tag v-for="rname in row.rolenames" :key="rname">
            {{ rname }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col" width="100">
        <template slot-scope="{ row }">
          <el-tag :type="row.state == '1' ? 'success' : 'danger'">
            {{ row.state == 1 ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        min-width="300px"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="info" size="mini" @click="handleEditPassword(row)">
            修改密码
          </el-button>
          <el-button size="mini" type="success" @click="handleAddrole(row)">
            分配角色
          </el-button>
          <el-button size="mini" type="danger" @click="deleteAdmin(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="getUserList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="adminDto"
        label-position="left"
        label-width="90px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="昵称" prop="username">
          <el-input v-model="adminDto.username" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="adminDto.state"
            clearable
            placeholder="用户状态"
            style="width: 150px;"
            class="filter-item"
            readonly="readonly"
          >
            <el-option style="width: auto" label="启用" :value="1"
              >启用</el-option
            >
            <el-option style="width: auto" label="停用" :value="0"
              >停用</el-option
            >
          </el-select>
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model="adminDto.account" />
        </el-form-item>
        <el-form-item
          v-if="dialogStatus === 'create'"
          label="手机号"
          prop="phone"
        >
          <el-input v-model="adminDto.phone" />
        </el-form-item>
        <el-form-item v-if="dialogStatus === 'create'" label="密码" prop="pwd">
          <el-input v-model="adminDto.pwd" type="password" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel(1)">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改密码" :visible.sync="editdialog">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="adminDto"
        label-position="left"
        label-width="90px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="密码">
          <el-input v-model="adminDto.pwd" type="password" value="123" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel(2)">
          取消
        </el-button>
        <el-button type="primary" @click="editPassword()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="分配角色" :visible.sync="addroledialog">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="adminDto"
        label-position="left"
        label-width="90px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="角色">
          <el-checkbox-group v-model="adminDto.rolenames">
            <el-checkbox
              v-for="role in adminDto.roles"
              :key="role.id"
              :label="role.roleName"
              >{{ role.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel(3)">
          取消
        </el-button>
        <el-button type="primary" @click="addrole()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUserList,
  addUser,
  editPassword,
  edit,
  addrole,
  deleteAdmin
} from '@/api/user';
import { getRoles } from '@/api/role';
import waves from '@/directive/waves'; // waves directive
import Pagination from '@/components/Pagination'; // secondary package based on el-pagination
export default {
  name: 'BackUserindex',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      };
      return statusMap[status];
    }
  },
  data() {
    return {
      columns: [
        {
          label: 'Checkbox',
          checkbox: true
        },
        {
          label: '',
          key: 'id',
          expand: true
        },
        {
          label: 'Event',
          key: 'event',
          width: 200,
          align: 'left'
        },
        {
          label: 'Scope',
          key: 'scope'
        }
      ],
      tableData: [],
      total: 0,
      tableKey: 0,
      listQuery: {
        current: 1,
        size: 10,
        username: ''
      },
      adminDto: {
        id: undefined,
        username: '',
        state: 0,
        roleId: 1,
        roles: [{ id: 1, roleName: 'super' }, { id: 2, roleName: 'admin' }]
      },
      dialogFormVisible: false,
      editdialog: false,
      addroledialog: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      dialogPvVisible: false,
      rules: {
        type: [
          { required: true, message: 'type is required', trigger: 'change' }
        ],
        timestamp: [
          {
            type: 'date',
            required: true,
            message: 'timestamp is required',
            trigger: 'change'
          }
        ],
        pwd: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 11 个字符', trigger: 'blur' }
        ],
        account: [
          { required: true, message: '账号不能为空', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ]
      },
      listLoading: false
    };
  },
  created() {
    this.getUserList(this.listQuery);
    this.getRoles();
  },
  methods: {
    // 获取用户列表
    async getUserList(listQuery) {
      const res = await getUserList(this.listQuery);
      this.tableData = res.data.data.data;
      const listlength = res.data.data.count;
      this.total = listlength;
    },
    // getRoles
    async getRoles() {
      const res = await getRoles();
      this.roles = res.data.data.data;
      this.adminDto.roles = this.roles;
      // console.log(this.adminDto.roles)
    },
    handleFilter() {
      this.listQuery.current = 1;
      this.getUserList(this.listQuery);
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      });
      row.status = status;
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === 'id') {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id';
      } else {
        this.listQuery.sort = '-id';
      }
      this.handleFilter();
    },
    cancel(type) {
      if (type === 1) {
        this.dialogFormVisible = false;
        this.getUserList();
      }
      if (type === 2) {
        this.editdialog = false;
      }
      if (type === 3) {
        this.addroledialog = false;
        this.getUserList();
      }
    },
    resetTemp() {
      this.adminDto = {
        id: undefined,
        username: '',
        gmtDatetime: '',
        state: 0,
        roleId: 1,
        roles: [{ id: 1, role: 'super' }, { id: 2, role: 'admin' }]
      };
    },
    handleCreate() {
      this.adminDto = {
        id: undefined,
        username: '',
        state: 0,
        roleId: 1
      };
      this.adminDto.roles = this.roles;
      this.dialogStatus = 'create';
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate();
      });
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          addUser(this.adminDto).then(() => {
            this.getUserList();
            this.dialogFormVisible = false;
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            });
          });
        }
      });
    },
    handleUpdate(row) {
      this.adminDto = row;
      this.adminDto.roles = this.roles;
      this.dialogStatus = 'update';
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate();
      });
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          edit(this.adminDto).then(() => {
            // this.getUserList()
            this.dialogFormVisible = false;
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            });
          });
        }
      });
    },
    handleEditPassword(row) {
      this.adminDto = row;
      this.adminDto.roles = this.roles;
      this.adminDto.pwd = '';
      this.editdialog = true;
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate();
      });
    },
    editPassword() {
      editPassword(this.adminDto).then(res => {
        if (res.data.code === 100001) {
          this.$notify({
            title: 'Error',
            message: 'Update fail ' + res.data.msg,
            type: 'error',
            duration: 2000
          });
        } else if (res.data.code !== 200) {
          this.$notify({
            title: 'Error',
            message: 'Update Error' + res.data.msg,
            type: 'fail',
            duration: 2000
          });
        } else {
          this.getUserList();
          this.$notify({
            title: 'Success',
            message: 'Update Success' + res.data.msg,
            type: 'success',
            duration: 2000
          });
        }
        this.editdialog = false;
      });
    },
    handleAddrole(row) {
      this.adminDto = row;
      this.adminDto.roles = this.roles;
      this.addroledialog = true;
    },
    // 分配角色
    addrole() {
      var userRoles = this.adminDto.rolenames;
      var roleIds = [];
      this.roles.forEach(element => {
        userRoles.forEach(element2 => {
          if (element.roleName === element2) {
            roleIds.push(element.id);
          }
        });
      });
      this.adminDto.roleIds = roleIds;
      addrole(this.adminDto).then(res => {
        if (res.data.code === 100001) {
          this.$notify({
            title: 'Error',
            message: 'addrole fail ' + res.data.msg,
            type: 'error',
            duration: 2000
          });
        } else if (res.data.code !== 200) {
          this.$notify({
            title: 'Error',
            message: 'addrole Error' + res.data.msg,
            type: 'fail',
            duration: 2000
          });
        } else {
          this.getUserList();
          this.$notify({
            title: 'Success',
            message: 'addrole success' + res.data.msg,
            type: 'success',
            duration: 2000
          });
        }
        this.addroledialog = false;
      });
    },
    async deleteAdmin(row) {
      var that = this;
      this.$confirm('删除提示！', '确认删除吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        deleteAdmin({ id: row.id }).then(res => {
          if (res.data.code === 200) {
            that.getUserList();
          }
        });
      });
    }
  }
};
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
